﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using EMC;
using System.IO;
using System.Reflection;

namespace FileServer
{

    public class Connections
    {
        private Socket listenSocket;
        private String addressOfServer;
        private String downloadTo;
        private bool running;

        public Connections(Dictionary<string, string> options)
        {
            addressOfServer = options["addressofserver"];
            downloadTo = options["Downloaddir"];
        }

        public void stop()
        {
            running = false;
            listenSocket.Close();
        }

        public void start()
        {
            running = true;
            ListenForClients();
        }

        private void ListenForClients()
        {
            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress[] ipAddress = Dns.GetHostAddresses(addressOfServer);
            listenSocket.Bind(new IPEndPoint(ipAddress[0], 5656));


            while (running == true)
            {
                listenSocket.Listen(100);
                Socket newcon = listenSocket.Accept();

                Thread handelness = new Thread(new ParameterizedThreadStart(HandleClient));
                handelness.Name = "Handle the Client";
                handelness.Start(newcon);
            }

            listenSocket.Close();
        }

        private void HandleClient(object client)
        {

            Socket clientSock = (Socket)client;
            FileHandler fileHandler = new FileHandler(clientSock, downloadTo);
            UserHandler userHandler = new UserHandler(clientSock);

            while (running == true)
            {
                string mess = recMess(clientSock);
                string[] message = mess.Split(',');
                Thread.Sleep(10);
                if (message[0] == "$FRANK")
                {
                    if (message[1] == "FILE")
                    {
                       System.Diagnostics.Debug.WriteLine(fileHandler.handleFile(message));
                    }
                    else if (message[1] == "USER")
                    {
                        System.Diagnostics.Debug.WriteLine(userHandler.handleUser(message));
                    }

                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Messge recived is not the Proper format");
                }


            }
        }
        private void sendMessage(Socket clientSocket, string protocolMessage)
        {

            byte[] sendmess = Encoding.UTF8.GetBytes(protocolMessage);

            System.Diagnostics.Debug.WriteLine("Message sent: " + protocolMessage);

            clientSocket.Send(sendmess);

        }

        private string recMess(Socket incomming)
        {
            byte[] buffer = new byte[1024];

            incomming.Receive(buffer);
            System.Diagnostics.Debug.WriteLine("Message Recived: " + Encoding.UTF8.GetString(buffer));
            return Encoding.UTF8.GetString(buffer);

        }
    }
}
/*#############SERVER PROTOCOL STRINGS++++++++++++++++
 * Start by selecting the Server
 * $FRANK
 * now Add what follows 
 */

/*##############FILE PROTOCOL STRINGS++++++++++++++++++++++
 *  Define what catergoy
 *  "FILE"
 * Define Function
 *      UPLOAD  Upload a file
 *          PATH    Directory of where to save the File
 *          NAME    Name of the File
 *          DESC    Descripiton of the File
 *          USER    User ID of the User who uploaded it.
 *      DOWNLOAD Download a File
 *EG
 *  To Send a File use the string 
 *  $FRANK,FILE,UPLOAD,<PARAMERTERS>,
 *  
 */


/*##############USER PROTOCOL STRINGS++++++++++++++++++++++
 *  Define what catergoy
 *  "USER"
 * Define Function
 *      CREATE  Create a User
 *      GET     Get User Data
 *      DELETE  DELETE A USER
 *      LOGIN   Log a User in
 */

//if (message[2] == "UPLOAD")
//{

//}
//else if (message[2] == "DOWNLOAD")
//{
//    System.Diagnostics.Debug.WriteLine("Retrive the File");
//}



//int bufferSize = 1000;
//                            System.Diagnostics.Debug.WriteLine("Reciving Data");
//                            int receivedBytesLen = 0;
//                            FileStream neofiledata = new FileStream(downloadTo, FileMode.Append, FileAccess.Write);

//                            byte[] buffer = new byte[bufferSize];

//                           do
//                            {
//                                Thread.Sleep(1);
//                                receivedBytesLen = clientSock.Receive(buffer);
//                                neofiledata.Write(buffer, 0, bufferSize);
//                                //System.Diagnostics.Debug.WriteLine("Bytes Recived: " + receivedBytesLen);

//                            } while (bufferSize == receivedBytesLen);
//                            System.Diagnostics.Debug.WriteLine("File Completed");
//                            neofiledata.Close();

//                        }


//    else if (message[1] == "USER")
//    {
//        System.Diagnostics.Debug.WriteLine("User Functions");
//        if (message[2] == "CREATE")
//        {
//            System.Diagnostics.Debug.WriteLine("Create a User");
//        }
//        else if (message[2] == "GET")
//        {
//            System.Diagnostics.Debug.WriteLine("Get User Data");
//        }
//        else if (message[2] == "DELETE")
//        {
//            System.Diagnostics.Debug.WriteLine("DELETE A USER");
//        }
//    }